<template>
  <div class="firmware">
    <div class="tools-container" style="margin-top: 20px; margin-left: 20px">
      <div class="buttons">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addClickShow">新增版本</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <el-table ref="table" v-loading="listLoading" :data="tableData" class="table-container" element-loading-text="加载中..." border center style="width: 95%; margin:0 auto">
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column prop="version" label="版本号" />
      <el-table-column prop="remark" label="备注" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditClick(scope.row)">备注修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="downLoad(scope.row)">下载</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 组件 -->
    <el-pagination :current-page.sync="pageJson.page" :page-size="pageJson.size" :total="total" :page-sizes="[10,20,30,50]" class="pagination-container" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    <!-- 新增 -->
    <el-dialog title="新增" :visible.sync="addShow" width="60%">
      <el-form ref="addForm" :model="addForm" label-width="100px" :rules="rule">
        <el-form-item label="版本号" prop="version">
          <el-input v-model="addForm.version" />
        </el-form-item>
        <el-form-item label="文件上传" prop="text">
          <el-upload
            ref="upload"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-change="handleChange"
            :on-success="handleSuccPic"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :action="uploadUrl"
            name="file"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传bin文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addShow = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateClick('addForm')">创 建</el-button>
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="备注修改" :visible.sync="editShow" width="60%">
      <el-form ref="editForm" :model="editForm" label-width="100px" :rules="rule">
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editShow = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit('editForm')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFirmware, addFirmware, editFirmware, delFirmware } from '@/api/firmware'

export default {
  name: 'Firmware',
  data() {
    return {
      listLoading: true,
      uploadUrl: process.env.VUE_APP_BASE_API + '/portal/upload/upload',
      downloadUrl: process.env.VUE_APP_BASE_API + 'portal/upload/download',
      fileList: [],
      tableData: [],
      pageJson: {
        page: 1,
        size: 10
      },
      total: 0,
      addShow: false,
      addForm: {
        version: '',
        text: '',
        remark: ''
      },
      editShow: false,
      editForm: {
        remark: ''
      },
      rule: {
        version: [
          { required: true, message: '请输入版本号', trigger: 'blur' }
        ],
        text: [
          { required: true, message: '请选择文件', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    // 获取数据
    getData() {
      const { page, size } = this.pageJson
      getFirmware({
        page,
        size
      }).then(res => {
        if (res.ok) {
          this.tableData = res.data.records
          this.total = res.data.total
          this.listLoading = false
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageJson.size = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.pageJson.page = val
      this.getData()
    },
    // 新增弹出
    addClickShow() {
      this.fileList = []
      this.addShow = true
    },
    handleCreateClick(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { remark, text, version } = this.addForm
          addFirmware({
            remark,
            text,
            version
          }).then(res => {
            if (res.ok) {
              this.$message({
                message: res.data,
                type: 'success',
                duration: 800
              })
              this.addShow = false
              this.getData()
              this.addForm = {
                remark: '',
                text: '',
                version: ''
              }
            }
          })
        }
      })
    },
    // 下载
    downLoad(data) {
      // const base = process.env.VUE_APP_BASE_API
      // window.location.href = base.split(':')[0] + ':' + base.split(':')[1] + '/' + data.text
      window.location.href = `${this.downloadUrl}?filename=${data.text}`
    },
    // 修改打开
    handleEditClick(data) {
      this.editShow = true
      this.editForm = {
        fid: data.id,
        remark: data.remark
      }
    },
    // 修改提交
    handleEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { fid, remark } = this.editForm
          editFirmware({
            fid,
            remark
          }).then(res => {
            if (res.ok) {
              this.$message({
                message: res.data,
                type: 'success',
                duration: 800
              })
              this.editShow = false
              this.getData()
            }
          })
        }
      })
    },
    // 删除
    handleDeleteClick(data) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFirmware(data.id).then(res => {
          if (res.ok) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 800
            })
            this.getData()
          }
        })
      }).catch(() => {
        console.log('取消删除')
      })
    },
    // 限制的钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 移除之前的钩子
    beforeRemove(file, fileList) {
      if (file && file.status === 'ready') {
        return this.$confirm(`确定移除${file.name}？`)
      }
    },
    // 移除完成的钩子
    handleRemove(file, fileList) {
      this.addForm.text = ''
    },
    // 改变图片触发
    handleChange(file, fileList) {
      const isJPG =
        file.raw.type === 'application/octet-stream'
      if (!isJPG) {
        this.$message.error('文件格式为bin')
        this.fileList.splice(0, 1)
      } else {
        // todo 将文件上传
        this.$refs.upload.submit()
      }
    },
    handleSuccPic(file, fileList) {
      this.addForm.text = file.data
    }
  }
}
</script>
